package com.adt.studioms.api;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.adt.studioms.om.Operator;
import com.asao.baseware.core.api.hibernate.HibernateDAOAwareAPI;
import com.asao.baseware.core.security.MD5;

public class OperatorAPI extends HibernateDAOAwareAPI<Operator> {

    protected Class<Operator> getEntityClass() {
        return Operator.class;
    }

    public Operator createOperator(String code,
                                   String role,
                                   String name, 
                                   String loginName, 
                                   String password, 
                                   String address, 
                                   String phone, 
                                   Long dateOfBirth, 
                                   Long dateOfMarriage) {
        Operator op = new Operator();
        op.setCode(code);
        op.setRole(role);
        op.setName(name);
        op.setLoginName(loginName);
        op.setPassword(MD5.instance().md5(password.getBytes()));
        op.setAddress(address);
        op.setPhone(phone);
        op.setDateOfBirth(dateOfBirth);
        op.setDateOfMarriage(dateOfMarriage);
        
        dao.save(op);
        return op;
    }
    
    public Operator getByLoginName(String loginName) {
        DetachedCriteria criteria = DetachedCriteria.forClass(getEntityClass());
        criteria.add(Restrictions.eq("loginName", loginName));
        
        List<Operator> ops = dao.findByCriteria(criteria, 0, 1);
        return ops.size()>0 ? ops.get(0) : null;
    }
    
    public boolean resetPassword(String loginName, String newPassword) {
        Operator op = getByLoginName(loginName);
        if (op!=null) {
            op.setPassword(newPassword);
            dao.update(op);
            return true;
        }
        
        return false;
    }
    
    public boolean changePassword(String loginName, String oldPassword, String newPassword) {
        Operator op = getByLoginName(loginName);
        if (op!=null) {
            if (op.getPassword().equals(MD5.instance().md5(oldPassword.getBytes()))) {
                op.setPassword(newPassword);
                dao.update(op);
                return true;
            }
        }
        
        return false;
    }
}
